package com.lwj.liwanjia.view.fragment.shop;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lwj.liwanjia.MainActivity;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.GwAdapter;
import com.lwj.liwanjia.base.BaseFragment;
import com.lwj.liwanjia.bean.DeleteAllBean;
import com.lwj.liwanjia.bean.DeleteBean;
import com.lwj.liwanjia.bean.GwcBean;
import com.lwj.liwanjia.bean.JieSuanBean;
import com.lwj.liwanjia.bean.PriceBean;
import com.lwj.liwanjia.bean.PriceBean1;
import com.lwj.liwanjia.bean.SelectBean;
import com.lwj.liwanjia.bean.SelectDpBean;
import com.lwj.liwanjia.bean.ToJieSuanBean;
import com.lwj.liwanjia.impl.DeleteGwcView;
import com.lwj.liwanjia.impl.GwcView;
import com.lwj.liwanjia.impl.JieSuanView;
import com.lwj.liwanjia.presenter.DeleteGwcPresenter;
import com.lwj.liwanjia.presenter.GwcPresenter;
import com.lwj.liwanjia.presenter.JieSuanPresenter;
import com.lwj.liwanjia.utils.FragNavController;
import com.lwj.liwanjia.utils.RxBus;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.dianpu.DianpuActivity;
import com.lwj.liwanjia.view.activity.indent.IndentActivity;
import com.lwj.liwanjia.view.activity.login.LoginActivity;
import com.roughike.bottombar.BottomBar;
import com.superrecycleview.superlibrary.adapter.SuperBaseAdapter;
import com.superrecycleview.superlibrary.recycleview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 购物车
 */
public class ShopFragment extends BaseFragment implements GwcView, DeleteGwcView, JieSuanView {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.shop_rlv)
    SuperRecyclerView shopRlv;
    @BindView(R.id.tv_zongjia)
    TextView tvZongjia;
    @BindView(R.id.cb_all)
    CheckBox checkBox;
    @BindView(R.id.tv_jiesuan)
    TextView tvJiesuan;
    @BindView(R.id.progress)
    ProgressBar progressBar;
    @BindView(R.id.rl_jiesuan)
    RelativeLayout rlJiesuan;
    @BindView(R.id.zanwugouwu)
    RelativeLayout noShop;

    private List<GwcBean.DataBean> list = new ArrayList<>();//所有商品
    private GwAdapter adapter;
    private GwcPresenter gwcPresenter;
    private String token;
    private double allPrice = 0.00;
    private DeleteGwcPresenter delterPresenter;
    private List<DeleteAllBean.DataBean> dataList = new ArrayList<>();//删除商品
    private JieSuanPresenter jieSuanPresenter;
    private List<ToJieSuanBean.DataBean> jieSuanList = new ArrayList<>();
    private Subscription subscription;
    private Subscription subscribe;
    private Subscription subscription1;
    private Subscription subscribe1;
    public boolean isGuestLogin = false;

    @Override
    protected void initView(View view) {
        tvTitle.setText("购物车");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("编辑");
        tvZongjia.setText("￥" + String.format("%.2f", allPrice));
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        shopRlv.setLayoutManager(manager);
        shopRlv.setRefreshEnabled(false);
        shopRlv.setLoadMoreEnabled(false);
        adapter = new GwAdapter(getActivity(), list);
        shopRlv.setAdapter(adapter);
        gwcPresenter = new GwcPresenter(this);
        delterPresenter = new DeleteGwcPresenter(this);
        jieSuanPresenter = new JieSuanPresenter(this);
        listener();
        refreshData();
    }

    @Override
    protected void initData() {
    }

    private void refreshData() {
        //点击商品按钮选择
        subscription = RxBus.getInstance().toObserverable(SelectBean.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<SelectBean>() {
            @Override
            public void call(SelectBean selectBean) {
                if (selectBean.isCheckAll()) {
                    list.get(selectBean.getPosition()).getShopInfo().setDianpuCheck("true");
                    if (selectBean.getDianpuSum() == list.size()) {
                        checkBox.setChecked(true);
                    }
                } else {
                    //但点铺之前是选中的时候总的店铺选中数量才减1
                    if (list.get(selectBean.getPosition()).getShopInfo().getDianpuCheck().equals("true")) {
                        selectBean.setDianpuSum(selectBean.getDianpuSum() - 1);
                    }
                    list.get(selectBean.getPosition()).getShopInfo().setDianpuCheck("false");
                    checkBox.setChecked(false);
                }
                adapter.setSum(selectBean.getDianpuSum());
                adapter.notifyDataSetChanged();
            }
        });
        //点击具体的某个商品计算价格
        subscribe = RxBus.getInstance().toObserverable(PriceBean.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<PriceBean>() {
            @Override
            public void call(PriceBean priceBean) {
                int checkPosition = priceBean.getCheckPosition();
                int dpPosition = priceBean.getDpPosition();
                List<GwcBean.DataBean.GoodsBean> goods = list.get(dpPosition).getGoods();
                int commodityNum = goods.get(checkPosition).getCommodityNum();
                if (priceBean.isCheck()) {
                    allPrice += (goods.get(checkPosition).getPrice()) * commodityNum;
                } else {
                    allPrice -= (goods.get(checkPosition).getPrice()) * commodityNum;
                }
                tvZongjia.setText("￥" + String.format("%.2f", allPrice));
            }
        });
        //点击店铺选择该店铺下的所有商品计算价格
        subscription1 = RxBus.getInstance().toObserverable(SelectDpBean.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<SelectDpBean>() {
            @Override
            public void call(SelectDpBean selectDpBean) {
                List<GwcBean.DataBean.GoodsBean> goods = list.get(selectDpBean.getPosition()).getGoods();
                List<Integer> integers = selectDpBean.getIntegers();
                if (selectDpBean.isCheck()) {
                    if (integers.size() > 0) {
                        for (int j = 0; j < integers.size(); j++) {
                            int commodityNum = goods.get(integers.get(j)).getCommodityNum();
                            allPrice -= (goods.get(integers.get(j)).getPrice()) * commodityNum;
                        }
                    }
                    for (int i = 0; i < goods.size(); i++) {
                        int commodityNum = goods.get(i).getCommodityNum();
                        allPrice += (goods.get(i).getPrice()) * commodityNum;
                    }
                    if (selectDpBean.getSum() == list.size()) {
                        checkBox.setChecked(true);
                    }
                } else {
                    if (integers.size() > 0) {
                        for (int j = 0; j < integers.size(); j++) {
                            int commodityNum = goods.get(integers.get(j)).getCommodityNum();
                            allPrice += (goods.get(integers.get(j)).getPrice()) * commodityNum;
                        }
                    }
                    for (int i = 0; i < goods.size(); i++) {
                        int commodityNum = goods.get(i).getCommodityNum();
                        allPrice -= (goods.get(i).getPrice()) * commodityNum;
                    }
                    if (selectDpBean.getSum() < list.size()) {
                        checkBox.setChecked(false);
                    }
                }
                tvZongjia.setText("￥" + String.format("%.2f", allPrice));
            }
        });
        //商品选中后再次改变数量
        subscribe1 = RxBus.getInstance().toObserverable(PriceBean1.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<PriceBean1>() {
            @Override
            public void call(PriceBean1 priceBean1) {
                int checkPosition = priceBean1.getCheckPosition();
                int dpPosition = priceBean1.getDpPosition();
                List<GwcBean.DataBean.GoodsBean> goods = list.get(dpPosition).getGoods();
                if (priceBean1.isFlag()) {//添加数量后
                    allPrice += goods.get(checkPosition).getPrice();
                } else {
                    allPrice -= goods.get(checkPosition).getPrice();
                }
                tvZongjia.setText("￥" + String.format("%.2f", allPrice));
            }
        });
    }

    private void listener() {
        //进入店铺
        adapter.setOnItemClickListener(new SuperBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object item, int position) {
                Intent intent = new Intent(getActivity(), DianpuActivity.class);
                intent.putExtra("shopInfoId", list.get(position).getShopInfo().getShopInfoId());
                startActivity(intent);
            }
        });

    }

    // 数据归零
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getData();
            dataList.clear();
            jieSuanList.clear();
            allPrice = 0.00;
            checkBox.setChecked(false);
            tvZongjia.setText("￥" + String.format("%.2f", allPrice));
            adapter.setSum(0);
            tvJiesuan.setText("结算");
            tvJiesuan.setBackgroundColor(getActivity().getResources().getColor(R.color.colorEC921A));
            tvRight.setText("编辑");
            shopRlv.scrollToPosition(0);
        }
    }


    public void getData() {
        token = SpfUtils.getSpfUtils(getActivity()).getToken();
        gwcPresenter.getGwcData(token);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_shop;
    }


    @OnClick({R.id.cb_all, R.id.tv_jiesuan, R.id.tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cb_all://全选
                allPrice = 0.00;
                if (checkBox.isChecked()) {
                    adapter.setSum(list.size());
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).getShopInfo().setDianpuCheck("true");
                        List<GwcBean.DataBean.GoodsBean> goods = list.get(i).getGoods();
                        for (int j = 0; j < goods.size(); j++) {
                            int commodityNum = goods.get(j).getCommodityNum();
                            allPrice += (goods.get(j).getPrice()) * commodityNum;
                        }
                    }
                } else {
                    adapter.setSum(0);
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).getShopInfo().setDianpuCheck("false");
                    }
                }
                tvZongjia.setText("￥" + String.format("%.2f", allPrice));
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_jiesuan://结算
                if ("删除".equals(tvJiesuan.getText().toString())) {
                    DeleteAllBean deleteBean = new DeleteAllBean();
                    for (int i = 0; i < list.size(); i++) {
                        List<GwcBean.DataBean.GoodsBean> goods = list.get(i).getGoods();
                        //选中了店铺
                        if (list.get(i).getShopInfo().getDianpuCheck().equals("true")) {
                            for (int j = 0; j < goods.size(); j++) {
                                DeleteAllBean.DataBean data = new DeleteAllBean.DataBean();
                                data.setCommodityCode(goods.get(j).getCommodityCode());
                                data.setCommodityType(goods.get(j).getCommodityType());
                                dataList.add(data);
                            }
                        } else {
                            //未选中店铺，但是该店铺下某些物品选中
                            for (int j = 0; j < goods.size(); j++) {
                                if (goods.get(j).getShangpinCheck().equals("true")) {
                                    DeleteAllBean.DataBean data = new DeleteAllBean.DataBean();
                                    data.setCommodityCode(goods.get(j).getCommodityCode());
                                    data.setCommodityType(goods.get(j).getCommodityType());
                                    dataList.add(data);
                                }
                            }
                        }
                    }
                    deleteBean.setDataBeanList(dataList);
                    if (dataList.size() > 0) {
                        delterPresenter.deleteGwc(token, deleteBean);
                    } else {
                        Toast.makeText(getActivity(), "未选择商品", Toast.LENGTH_SHORT).show();
                    }
                } else if ("结算".equals(tvJiesuan.getText().toString())) {
                    ToJieSuanBean jiesuan = new ToJieSuanBean();
                    for (int i = 0; i < list.size(); i++) {
                        List<GwcBean.DataBean.GoodsBean> goods = list.get(i).getGoods();
                        //选中了店铺
                        if (list.get(i).getShopInfo().getDianpuCheck().equals("true")) {
                            for (int j = 0; j < goods.size(); j++) {
                                ToJieSuanBean.DataBean data = new ToJieSuanBean.DataBean();
                                data.setCommodityCode(goods.get(j).getCommodityCode());
                                data.setCommodityType(goods.get(j).getCommodityType());
                                jieSuanList.add(data);
                            }
                        } else {
                            //未选中店铺，但是该店铺下某些物品选中
                            for (int j = 0; j < goods.size(); j++) {
                                if (goods.get(j).getShangpinCheck().equals("true")) {
                                    ToJieSuanBean.DataBean data = new ToJieSuanBean.DataBean();
                                    data.setCommodityCode(goods.get(j).getCommodityCode());
                                    data.setCommodityType(goods.get(j).getCommodityType());
                                    jieSuanList.add(data);
                                }
                            }
                        }
                    }
                    jiesuan.setDataBeanList(jieSuanList);
                    if (jieSuanList.size() > 0) {
                        jieSuanPresenter.toJieSuan(token, jiesuan);
                    } else {
                        Toast.makeText(getActivity(), "未选择结算的商品", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.tv_right://编辑、完成
                if ("编辑".equals(tvRight.getText().toString())) {
                    tvRight.setText("完成");
                    tvJiesuan.setText("删除");
                    tvJiesuan.setBackgroundColor(getActivity().getResources().getColor(R.color.colorFF3B15));
                } else if ("完成".equals(tvRight.getText().toString())) {
                    tvRight.setText("编辑");
                    tvJiesuan.setBackgroundColor(getActivity().getResources().getColor(R.color.colorEC921A));
                    tvJiesuan.setText("结算");
                }
                break;
        }
    }

    @Override
    public void showProgress() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgress() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(getActivity(), "数据加载失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
        allPrice = 0.00;
        checkBox.setChecked(false);
        tvZongjia.setText("￥" + String.format("%.2f", allPrice));
        adapter.setSum(0);
        tvJiesuan.setText("结算");
        tvJiesuan.setBackgroundColor(getActivity().getResources().getColor(R.color.colorEC921A));
        tvRight.setText("编辑");
        shopRlv.scrollToPosition(0);
    }

    //    结算
    @Override
    public void toJieSuan(JieSuanBean jieSuanBean) {
        if (jieSuanBean.getState() == 0) {
            jieSuanList.clear();
            Toast.makeText(getActivity(), "结算失败", Toast.LENGTH_SHORT).show();
        } else {
            jieSuanList.clear();
            Intent intent = new Intent(getActivity(), IndentActivity.class);
            intent.putExtra("data", jieSuanBean.getData());
            startActivity(intent);
        }
    }

    //删除物品
    @Override
    public void deleteGwc(DeleteBean deleteBean) {
        if (deleteBean.isData()) {
            dataList.clear();
            getData();
            allPrice = 0.00;
            tvZongjia.setText("￥0.00");
        } else {
            Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
        }
    }

    //    获取购物车数据
    @Override
    public void getGwcData(GwcBean gwcBean) {
        if (gwcBean.getState() == 0) {
            startActivity(new Intent(getActivity(), LoginActivity.class).putExtra("type", "购物车"));
            getActivity().finish();
        } else {
            list.clear();
            list.addAll(gwcBean.getData());
            if (list.size() == 0) {
                rlJiesuan.setVisibility(View.GONE);
                noShop.setVisibility(View.VISIBLE);
            } else {
                rlJiesuan.setVisibility(View.VISIBLE);
                noShop.setVisibility(View.GONE);
            }
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroyView() {
        if (jieSuanPresenter != null) {
            jieSuanPresenter = null;
        }
        if (delterPresenter != null) {
            delterPresenter = null;
        }
        if (gwcPresenter != null) {
            gwcPresenter = null;
        }
        if (!subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
        if (!subscribe1.isUnsubscribed()) {
            subscribe1.unsubscribe();
        }
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
        if (!subscription1.isUnsubscribed()) {
            subscription1.unsubscribe();
        }
        super.onDestroyView();
    }
}
